/*
 *
 *  Copyright (C) 2009 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Resources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.LibreGeoSocial.App.Home;
import com.LibreGeoSocial.App.GeoNames.AltitudeManager;
import com.LibreGeoSocial.App.Routes.LocationService;

public class ResourceManager 
{
	public static final String PHOTO_RESOURCE  	= "panoramio";
	public static final String VIDEO_RESOURCE  	= "YOUTUBE";
	public static final String PLACES_RESOURCE 	= "11870";
	public static final String ALL_RESOURCE 	= "ALL";
	private static final String TAG 		= "Resource manager";
	private static final String TAG_ERROR 	= TAG + "::ERROR";
	
	static private ResourceManager singleton = null;
	
	private static ArrayList<ResourceItem> mPhotosResurce = new ArrayList<ResourceItem>();
	private static ArrayList<ResourceItem> mVideosResource = new ArrayList<ResourceItem>();
	private static ArrayList<ResourceItem> mPlacesResource = new ArrayList<ResourceItem>();
	
	private static String message = "";
	
	static public ResourceManager getInstance() 
	{
        if (singleton == null) {
            singleton = new ResourceManager();
        }
        return singleton;
		
	}
	
	public void addResource (ResourceItem item, String resource)
	{
		getList(resource).add(item);	
	}
	
	public ResourceItem getResource (Integer position, String resource)
	{
		return getList(resource).get(position);
	}
		
	public Integer getSize(String resource)
	{
		return getList(resource).size();
	}
	
	public boolean refreshList(String type){
		reset(type);
		return getJSON (type);
	}
	
	private boolean getJSON (String type)
	{
		
		try {
			String URL =  "http://test.libregeosocial.libresoft.es/agregador/rest/?tipo="+ type +"&latitud=" + 
							LocationService.getCurrentLocation().getLatitude() + "&longitud=" + 
							LocationService.getCurrentLocation().getLongitude() + "&radio=0.8&texto=&format=JSON";
			
            HttpGet get = new HttpGet(URL);
  
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();

            String str = convertStreamToString(entity.getContent());
            JSONObject json = new JSONObject(str);

            return parseJSON (json, type);
      
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            message = "getJSON: " + e.toString();
            return false;
        }
		
	}
	
    private String convertStreamToString (InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return sb.toString();

    }

    private boolean parseJSON (JSONObject json, String type) throws URISyntaxException
    {
    	JSONArray array;
    	
		try {
			array = json.getJSONArray("resources");
			int count = array.length();
			for (int i = 0; i < count; i++) {
				
				JSONObject obj = array.getJSONObject(i);
				String title, url, service, summary, date = null;
				Double latitude, longitude, altitude;
				
							
				title 		= obj.getString("title");
				summary 	= obj.getString("summary");
				date 		= obj.getString("date");
				url			= obj.getString("url");
				latitude	= obj.getDouble("latitude");
				longitude	= obj.getDouble("longitude");
				service 	= obj.getString("service");
				
				altitude = AltitudeManager.getAltitudeFromLatLong((float)(double)latitude, (float)(double)longitude);
				
				ResourceItem resource = null;

				if (service.equals(PLACES_RESOURCE))
				{
					resource = new ResourceItem (title, summary, date, 
												 latitude, longitude, 
												 altitude, url, service, null);
					
				}
				else if (service.equals(PHOTO_RESOURCE))
				{
					String owner, urlImage, urlThumb;
					
					owner 		= obj.getString("credits_owner");
					urlImage	= ""; 
					urlThumb  	= obj.getString("thumb_url");
					
					resource = new PanoramioItem (title, summary, date, 
												  latitude, longitude, 
												  altitude, url, 
												  service, null, owner, 
												  urlImage, urlThumb);
				}
				else
				{
					resource = new ResourceItem();
					Log.e(TAG_ERROR, "Unknown Resource\n");
				}
				
				addResource(resource,type);
				
			}
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.e(TAG_ERROR, e.toString());
			message = "parseJSON: " + e.toString();
			return false;
		}
	
    }
	
	public void reset(String type)
	{
		if (type.equals(PHOTO_RESOURCE))
			mPhotosResurce.clear();
		else if (type.equals(PLACES_RESOURCE))
			mPlacesResource.clear();
		else if (type.equals(VIDEO_RESOURCE))
			mVideosResource.clear();
		else if (type.equals(ALL_RESOURCE)){
			mPhotosResurce.clear();
			mVideosResource.clear();
			mPlacesResource.clear();
		}
	}

	public ArrayList<ResourceItem> getList (String resource)
	{
		
		if (resource.equals(PHOTO_RESOURCE))
			return mPhotosResurce;		
		else if (resource.equals(VIDEO_RESOURCE))
			return mVideosResource;
		
		else if (resource.equals(PLACES_RESOURCE))
			return mPlacesResource;
		else
			return null;
	}
	
	public String getMessage(){
		return message;
	}
}